
import random
from typing import List

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        if not grid or not grid[0]:
            return 0
        
        m, n = len(grid), len(grid[0])
        dp = [[0] * n for _ in range(m)]
        
        dp[0][0] = grid[0][0]
        
        for i in range(1, m):
            dp[i][0] = dp[i-1][0] + grid[i][0]
        
        for j in range(1, n):
            dp[0][j] = dp[0][j-1] + grid[0][j]
        
        for i in range(1, m):
            for j in range(1, n):
                dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
        
        return dp[m-1][n-1]

def test_solution():
    """测试函数"""
    solution = Solution()
    
    # 测试用例 [网格, 期望结果]
    test_cases = [
        ([[1, 3, 1], [1, 5, 1], [4, 2, 1]], 7),
        ([[1, 2, 3], [4, 5, 6]], 12),
        ([[1]], 1),
        ([[1, 2, 3, 4]], 10),
        ([[1], [2], [3]], 6)
    ]
    
    for i, (grid, expected) in enumerate(test_cases):
        result = solution.minPathSum(grid)
        status = "✓" if result == expected else "✗"
        print(f"测试 {i+1}: {status} 结果={result}, 期望={expected}")

if __name__ == "__main__":
    test_solution()
